package cn.wzptsoft.tinymallbe.controller;

import cn.wzptsoft.common.utils.JwtUtils;
import cn.wzptsoft.common.utils.Result;
import cn.wzptsoft.tinymallbe.dto.UserLoginDTO;
import cn.wzptsoft.tinymallbe.entity.User;
import cn.wzptsoft.tinymallbe.service.UserService;
import cn.wzptsoft.tinymallbe.vo.TokenVo;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * 登录与注册
 */
@RestController
@RequestMapping
public class LoginController {

    private final UserService userService;

    public LoginController(UserService userService) {
        this.userService = userService;
    }

    /**
     * 用户登录
     *
     * @param userLoginParam 账号密码
     * @return token
     */
    @PostMapping("/login")
    public Result<TokenVo> login(@RequestBody @Valid UserLoginDTO userLoginParam) {
        // 调用userService检验账号密码 获取用户信息
        User user = userService.login(userLoginParam);
        // 生成JWT 返回前端 用于后续其他接口的登录验证
        String jwt = JwtUtils.generateToken(user.getId());
        TokenVo token = new TokenVo(jwt);
        return Result.ok(token);
    }

}
